package fy.uap.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import org.apache.commons.logging.LogFactory;

import fy.config.FyConfig;
import fy.uap.bean.ERPMergerBean;
import fy.util.DBUtil;


public class ERPMergerDao {

	private static org.apache.commons.logging.Log log = LogFactory
			.getLog(ERPMergerDao.class);

	private String number;
	private String createDate;
	private List<ERPMergerBean> beans;
	private String company;
	private String ou_id;

	public void setCompany(String company) {
		this.company = company;
	}

	public void setOu_id(String ou_id) {
		this.ou_id = ou_id;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public void setCreateDate(String createDate) {
		this.createDate = createDate;
	}

	public void setBeans(List<ERPMergerBean> beans) {
		this.beans = beans;
	}

	public boolean save() {
		boolean success = false;
		Connection conn = null;
		PreparedStatement pst = null;
		try {
			conn = DBUtil.connect(FyConfig.getERP_DB_CONFIG());

			conn.setAutoCommit(false);

			pst = conn
					.prepareStatement("insert into apps.FYG_AP_VENDORS_unite ( erp_bm, erp_sm, uap_bm, uap_sm, oa_number,create_date,approve_date,syb,ou_id, from_site, to_site,OA_NUMBER_SEQUENCE) values(?,?,?,?,?,to_date(?,'yyyy-mm-dd'),sysdate,?,?,?,?,?)");
			ou_id =ou_id.replace("key_", "");
			for (int i = 0, size = beans.size(); i < size; i++) {
				pst.setString(1, beans.get(i).getOldCode());
				pst.setString(2, beans.get(i).getOldName());
				pst.setString(3, beans.get(i).getNewCode());
				pst.setString(4, beans.get(i).getNewName());
				pst.setString(5, number);
				pst.setString(6, createDate);
				pst.setString(7, company);
				pst.setString(8, ou_id);
				pst.setString(9, beans.get(i).getOldAddress());
				pst.setString(10, beans.get(i).getNewAddress());
				pst.setString(11, beans.get(i).getSerial());

				pst.addBatch();
			}
			pst.executeBatch();
			conn.commit();
			success = true;
		} catch (Exception e) {
			DBUtil.rollback(conn);
			e.printStackTrace();
			log.error("供应商合并审批表（ERP）数据写入ERP数据库异常，单据编号：" + number, e);
		} finally {
			DBUtil.setAutoCommit(conn, true);
			DBUtil.close(pst, conn);
		}
		return success;
	}
}
